//
//  NetWorkManager.swift
//  WeiBoDemo
//
//  Created by chaowen deng on 2021/3/29.
//

import Foundation
//import Alamofire


// 如果没定义一个方法，都要写一遍返回参数 completion: @escaping (Result<Data, Error>) -> Void ，比较多，就提出来
typealias NetworkRequestResult = Result<Data, Error>
typealias NetworkRequestCompletion = (NetworkRequestResult) -> Void

//private let NetworkApiBaseURL = "https://gitee.com/iOS_July/wei-bo-post-demo/raw/master/WeiBoDemo/WeiBoDemo/Resources/"
// 这里放开，是因为网络图片那里要用到，一搬是不放开的
let NetworkApiBaseURL = "https://gitee.com/iOS_July/wei-bo-post-demo/raw/master/WeiBoDemo/WeiBoDemo/Resources/"
//https://github.com/xiaoyouxinqing/PostDemo/raw/master/PostDemo/Resources/PostListData_recommend_1.json
//https://gitee.com/iOS_July/wei-bo-post-demo/raw/master/WeiBoDemo/WeiBoDemo/Resources/PostListData_recommend_1.json
class NetWorkManager {
    
    static let shared = NetWorkManager()
    var commonHeaders: HTTPHeaders { ["user_id": "123", "token": "xxxxxxxx"] }
    
    // 这里将init方法写为私有，则外部就只能通过shared访问
    private init() {}
    
    // 如果外部调用方法，却没使用返回值，会有警告，这里用 修饰，外部没使用返回值，也不会有警告
    @discardableResult
    /// Get请求
    /// - Parameters:
    ///   - path: url
    ///   - parameters: 参数
    ///   - completion: 回调逃逸闭包
    /// - Returns: DataRequest  一半都用不到这个返回，但某些场景需要取消已经发送过的请求，这里将其返回出去
    func requestGet(path: String, parameters: Parameters?, completion: @escaping NetworkRequestCompletion) -> DataRequest {
        return AF.request(NetworkApiBaseURL + path,
                   method: .get,
                   parameters: parameters,
                   headers: commonHeaders,
                   requestModifier: {$0.timeoutInterval = 15.0} )
            .responseData { response in
                switch response.result {
                case let .success(data): completion(.success(data))
                case let .failure(error): completion(.failure(error))
                }
            }
    }
    
    @discardableResult
    func requstPost(path: String, parameters: Parameters?, completion: @escaping NetworkRequestCompletion) -> DataRequest {
        AF.request(NetworkApiBaseURL + path,
                   method: .post,
                   parameters: parameters,
                   encoding: JSONEncoding.prettyPrinted,
                   headers: commonHeaders,
                   requestModifier: {$0.timeoutInterval = 15.0} )
            .responseData { response in
                switch response.result {
                case let .success(data): completion(.success(data))
                case let .failure(error): completion(.failure(error))
                }
            }
    }
    
    
}

/*
 //MARK: - 多图上传 UIImage 数组 [UIImage]
    class func IMGS(url:String,param:[String:Any],images:[UIImage],success: @escaping SuccessBlock) {
        let request = AF.upload(multipartFormData: { (mutilPartData) in
               for image in images {
                   // 图片压缩 在下篇博客 https://editor.csdn.net/md/?articleId=106528518
                   let imgData = UIImage.imageCompress(image: image)
                   mutilPartData.append(imgData, withName: "files", fileName: String(String.getCurrentTimeStamp()) + ".jpg", mimeType: "image/jpg/png/jpeg")
               }
               //有参数
               if param != nil {
                   for key in params.keys {
                       let value = params[key] as! String
                       let vData:Data = value.data(using: .utf8)!
                       mutilPartData.append(vData, withName: key)
                   }
               }
        }, to: url, usingThreshold: UInt64.init(), method: .post, headers: [], interceptor: nil, fileManager: FileManager())
        request.uploadProgress { (progress) in
//            SVProgressHUD.showInfo(withStatus: "正在上传图片")
        }
        request.responseJSON { (response) in
            print(response)
            DispatchQueue.global().async(execute: {
                switch response.result {
                case let .success(result):
                    do {
                        let resultDict:[String:Any] = result as! [String:Any]
                        DispatchQueue.main.async(execute: {
                            // type 1:部分上传成功,2:全部图片上传失败,0:全部上传成功
                            let resp_code: Int = (resultDict["resp_code"] as! Int)
                            switch resp_code {
                            case 0:
                                success(resultDict)
                            case 1:
                                SVProgressHUD.showError(withStatus: (resultDict["resp_msg"] as! String))
                            default:
                                SVProgressHUD.showError(withStatus: (resultDict["resp_msg"] as! String))
                            }
                        })
                    }
                case let .failure(error):
                    SVProgressHUD.dismiss()
                    print(error)
                }
            })
        }
    }
 
 */
